<?php
namespace control;
/*
*委外报工类
*/

class outProcessReportClass extends adIndexClass
{
    private const table = 'process_report';
    private const tableMx = 'process_report_detail';
    private const page = 'outProcessReport';
    private const title = '委外报工';
    public array $stateOption = ['草稿', '待确认', '已确认'];

    /*行政人事-出差记录-查询条件*/
    public function home()
    {
        $html = checkbox(array('name' => 'state', 'value' => $this->stateOption, 'checked' => ['草稿', '待确认'])) . clear;
        if ($this->power(self::page, "seeAll")) {
            $html .= selectMultiple(array("name" => "stid", "title" => "报工人", "table" => "staff", 'sqlField' => 'name', 'sqlId' => 'stid'));
        }
        $html .=
            selectMultiple(array("name" => "companyId","title" => "委外单位", "table" => "supplier",'where' => " coid = '" . self::$coid . "' and outsource = '是' order by time", 'sqlField' => 'name', 'sqlId' => 'id')).
            text(array('name' => 'orderNo', 'title' => '报工单号')) .
            text(array('name' => 'machiningOrderNo', 'title' => '生产派工单号')) .
            selectMultiple(array("name" => "processId", "title" => "工序", "table" => "process", 'where'=>"coid = '".self::$coid."'", 'sqlField' => 'name', 'sqlId' => 'id')) .
            text(array('name' => 'materialName', 'title' => '产品名称')) .
            select(array('name' => 'teamType', 'option' => explode('，', para('teamType')), 'title' => '班次')) .
            text(array("name" => "createTime", 'laydate' => ['range' => '~'], 'class' => 'width200', "title" => "班次日期-班次日期"));
        //返回
        return $this->homeFun($this->search($html));
    }

    /*行政人事-出差记录-查询结果*/
    public function homeSearch()
    {
        //全等查询数组
        $equal = array(
            'classify'=>'委外报工',
            'coid' => self::$coid,
            "teamType" => $this->post('teamType'),
            "processId" => $this->post('processId'),
            'companyId'=>$this->post('companyId')
        );
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//单据编号
        );
        //初始化
        $and = "";
        $mAnd = '';
        if ($this->post('machiningOrderNo')) {
            $and .= " and sendId in (select id from machining_send_order where  coid = '".self::$coid."' and orderNo like '%" . $this->post('machiningOrderNo') . "%')";
        }
        if ($this->post('materialName')) {
            $mAnd = " and name like '%" . $this->post('materialName') . "%'";
        }
        if ($mAnd) {
            $and .= " and  materialId in (select id from material where coid = '" . self::$coid . "' {$mAnd})";
        }
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), field: 'teamNo');
        }
        if ($this->post('state')) {
            //单据日期
            $and .= " and state in ('" . implode("','", $this->post('state')) . "')";
        }
        //如果没有查看所有员工请假记录的权限
        if (!$this->power(self::page, "seeAll")) {
            $and .= $this->seeSelf(self::page);
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "time desc"));

        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = array($checkAll, '报工单号', "生产派工单号", "委外单位", "工序", "产品编码", "产品名称", "规格型号", '单位', '产量', '良品数量', '不良品数量', '报工人', '状态');
        $url = root . "control/adIndex.html?cla=" . $this->get('cla') . "";

        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                'track'=> array("title" => "单据追踪", "click" => "newIframe('单据追踪','" . root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=委外报工&id=" . $array['id'] . "')"),
            );
            if ($array['state'] == '已确认') {
                unset($dominate['edit']);
            }
            $machiningSendOrder = query('machining_send_order', "id = '$array[sendId]'");
            $supplier = query('supplier', "id = '$array[companyId]'");
            $process = query('process', "id = '$array[processId]'");
//            $team = query('team', "id = '$array[teamId]'");
            $material = query('material', "id = '$array[materialId]'");
            //返回本行
            $tr[] = array(
                $this->dominate($dominate), $array['orderNo'], $machiningSendOrder['orderNo'], $supplier['name'], $process['name'],$material['code'], $material['name'], $material['model'], $machiningSendOrder['unit'],
                self::lostZero($array['yield'],'numPrecision'), $array['yield'] - $array['badNum'], self::lostZero($array['badNum'],'numPrecision'), self::findStaff($array['stid']), $array['state'],
            );
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "confirm")) {
            $button .= "<span onclick=\"layer('{$this->get('cla')}', 'batchConfirm', {'act': 'del'})\" class='spanButton'>批量确认</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }



    /**
     * 批量确认
     */
    public function batchConfirm(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                "提示：" => "是否批量确认所选数据？",
            ),
        )));
        //返回
        return $this->layer(array("title" => "批量确认", "height" => 165, "html" => $html, 'formTwo' => 'listForm'));
    }

    /**
     *  批量确认
     */
    public function batchConfirmEdit(): bool|string
    {
        $idArr = $this->post('listId');
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有" . self::title . "的编辑权限";
        } elseif (empty($idArr) || !is_array($idArr)) {
            $json['warn'] = "请选择数据";
        }  else {
            $field = [
                'state' => '已确认',
                'checkId'=>self::$stid,
                'confirmTime'=>$this->time
            ];
            $text = '';
            $json['warn'] = '';
            $x = 0;
            $this->startTrans();
            foreach ($idArr as $id) {
                $info = query(self::table, "id = '$id'");
                if (empty($info['yield']) || $info['yield'] <= 0) {
                    $json['warn'] = "委外报工单【{$info['orderNo']}】的产量不能小于0";
                    break;
                }
                if ($info['state'] !='已确认'){
                    $json['warn'] = update(array('table' => self::table, 'field' => $field, 'where' => " id  = '$id'"));
                    $bool = $this->qualityOrder($info['id']);
                    if ($bool !== true) {
                        $json['warn'] = "【{$info['orderNo']}】:" . $bool;
                    }
                    if ($json['warn'] == '更新成功') {
                        $x++;
                        $text .= "【{$info['orderNo']}】状态修改为：已确认<br>";
                        auditClass::operateRecord($info['id'],'委外报工','确认');
                    } else {
                        $text = '';
                        break;
                    }
                }
            }
            if ($text) {
                //添加日志
                $this->commitTrans();
                $text = $this->control['name'] . "批量确认了" . self::title . "如下：" . $text;
                $this->logText(["type" => self::page, "text" => $text]);
                $_SESSION['warn'] = '成功操作' . $x . '条数据';
                $json['warn'] = 2;
                //返回
            }else{
                $this->rollback();
            }
        }
        //返回
        return json_encode($json, 320);
    }



    /**
     * 编辑
     *
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id')?:suiji();
        $sourceId = $this->get('sourceId');
        $clockRuleTr = '';
        $info = query(self::table, " id = '" . $id . "' ");
        $machining_send_order = query('machining_send_order', "id = '$info[sendId]'");
        $reportNum = find(array('table'=>self::table,'where'=>"sendId = '$machining_send_order[id]'",'sum'=>"yield"));
        if ($sourceId){
            //从派工单那边生成报工
            $machining_send_order = query('machining_send_order', "id = '$sourceId'");
            $info['processId'] = $machining_send_order['processId'];
            $routing_detail = query('routing_detail',"id = '$machining_send_order[routingMxId]'");
            $info['valuationType'] = $routing_detail['valuationType'];
            $reportNum = find(array('table'=>self::table,'where'=>"sendId = '$machining_send_order[id]'",'sum'=>"yield"));
            $info['yield'] = self::formattingFigure($machining_send_order['num']-$reportNum,'numPrecision');
            $info['companyId'] = $machining_send_order['companyId'];
        }
        $process = query('process', "id = '$info[processId]'");
        $defectOption = $process['id'] ? explode('，', $process['defectType']) : [];
        $result = find(array('table' => self::tableMx, 'where' => " orderId = '$info[id]' order by list asc"));
        if (is_array($result['array']) && count($result['array']) > 0) {
            foreach ($result['array'] as $k => $array) {
                if ($k == 0) {
                    $button = "<span class='spanButton' style='margin-top: 0' onclick='addRow(this)'>添加</span>";
                } else {
                    $button = "<span class='spanButton' style='margin-top: 0' onclick='decRow(this)'>删除</span>";
                }
                $input = hidden(array('name' => 'mxId[]', 'value' => $array['id'])) . select(array('name' => 'problem[]', 'title' => '请选择', 'value' => $array['problem'], 'option' => $defectOption)) . text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'title' => '数量', 'value' => self::lostZero($array['num'],'numPrecision')));
                $clockRuleTr .= <<<efo
<div class='item_row'>{$input}{$button}</div>
efo;
            }
        } else {
            $button = "<span class='spanButton' style='margin-top: 0' onclick='addRow(this)'>添加</span>";
            $input = hidden(array('name' => 'mxId[]', 'value' => self::getId())) . select(array('name' => 'problem[]', 'title' => '请选择', 'option' => $defectOption)) . text(array('name' => 'num[]', 'title' => '数量', 'other' => self::digitalFiltering('numPrecision'), 'value' => ''));
            $clockRuleTr .= <<<efo
<div class='item_row'>{$input}{$button}</div>
efo;
        }
        $material = query('material', "id = '$machining_send_order[materialId]'");
        $materialName = $machining_send_order['id'] ? ($material['code'] . '-' . $material['name'] . '-' . $material['model']) : '';
        $planNum = $machining_send_order['id'] ? ($machining_send_order['num'] . $machining_send_order['unit']) : '';
        $supplier = query('supplier',"id = '$info[companyId]'");
        //表单
        $data['html'] = $this->layerEdit([
            "table" => [
                array(
                    must . "生产派工单号：" => hidden(array('name' => 'sendId', 'value' => $machining_send_order['id'])) . "<span id='machiningOrder'>{$machining_send_order['orderNo']}</span><span class='del-row-button' style='margin-left: 5px;cursor: pointer' onclick=\"layer('{$this->get('cla')}','addMaterial',{})\">选择</span>",
                ),
                array(
                    '委外单位：'=>"<div id='companyName'>{$supplier['name']}</div>"
                ),
                array(
                    must . "工序：" => "<div id='process'>" . $process['name'] . "</div>" . hidden(array('name' => 'processId', 'value' => $process['id'])),
                ),
                array(
                    "计价方式：" => "<div id='valuationType'>" . $info['valuationType'] . "</div>",
                ),
                array(
                    "物料：" => "<span id='material'>{$materialName}</span>",
                ),
                array(
                    '计划数量：' => "<span id='machiningNum'>{$planNum}</span>，已报工数量<span id='reportNum'>$reportNum {$machining_send_order['unit']}</span>",
                ),
                array(
                    must . "产量：" => text(array("name" => "yield", 'other' => self::digitalFiltering('numPrecision'),"value" => $info['yield'])),
                ),
                array(
                    "不良品数量：" => text(array("name" => "badNum", 'other' => self::digitalFiltering('numPrecision'), "value" => $info['badNum'])),
                ),
                array(
                    "缺陷类型：" => "<div class='row-li'>" . $clockRuleTr . "</div>",
                ),
                array(
                    "加工费：" => text(array("name" => "fee", 'other' => self::digitalFiltering(),'unit'=>static::$unit,"value" => $info['fee'])),
                ),
                array(
                    "开始结束时间：" => text(array("name" => "startTime", 'laydate' => ['type' => 'datetime'], "value" => self::null($info['startTime'], false))) . '- ' . text(array("name" => "endTime", 'laydate' => ['type' => 'datetime'], "value" => self::null($info['endTime'], false))),
                ),
                array(
                    "备注：" => textarea(array("name" => "text", "value" => $info['text'])),
                ),
            ],
            'hidden' => hidden(array('name' => 'id', 'value' => $info['id'] ?: $this->get('id'))),
            'button' => "<button class=\"button left-bottom\" onclick=\"subForm('{$this->get('cla')}EditForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')\">保存</button>",
        ]);
        //返回
        return $this->tab($data) . $this->js();
    }

    public function js(): string
    {
        return <<<efo
<script>
//获取班组员工
function getTeamStaff(e){
       let teamId = e.value;
       $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getTeamStaff',{teamId:teamId},function (res){
             $("#teamStaff").html(res.html)
         },'json');
}
 //添加一行
         function addRow(){
             let processId = $("[name='processId']").val();
             if (!processId){
                 msg('请先选择工序','error');
             }else{
                 $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addRow',{processId:processId},function (res){
                     $(".row-li").append(res.data);
                 },'json');
             }
         }
          //选择生产产品
    function addMaterial(){
             $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMaterialEdit',$("form[name='mxForm']").serialize(),function(res) {
                 if (res.warn ==2){
                    $('#outProcessReportAddMaterial').hide();
                    $("#machiningNum").html(res.planNum+res.unit);
                       $("#reportNum").html(res.reportNum+res.unit);
                     $("#companyName").html(res.companyName);
                    $("[name='yield']").val(res.planNum);
                    $("#process").empty().append(res.process);
                    $("[name='processId']").val(res.processId);
                    $("#machiningOrder").html(res.orderNo);
                    $("#line").html(res.lineName);
                    $("#material").html(res.materialName);
                    $("[name='sendId']").val(res.id);
                    $(".row-li").find("[name='problem[]']").empty().append(res.problem);
                    if (res.valuationType =='班组计件'){
                        $("#teamStaff").hide();
                    }else if(res.valuationType =='个人计件'){
                         $("#teamStaff").show();
                    }
                    $("#valuationType").html(res.valuationType)
                 }else{
                     msg(res.warn);
                 }
            },'json');
    }
</script>
efo;
    }

    /**
     * 根据班组获取员工
     */
    public function getTeamStaff(){
        $teamId = $this->post('teamId');
        $json['html'] = selectMultiple(array("name" => "teamStaffId", "title" => "员工", "table" => "staff", 'where' => "stid in (select stid from team_detail where orderId = '$teamId' and coid = '" . self::$coid . "')", 'sqlField' => 'name', 'sqlId' => 'stid'));
        return json_encode($json,320);
    }
    /**
     * 添加一行
     *
     * @return bool|string
     */
    public function addRow()
    {
        $process = query('process', "id = '" . $this->post('processId') . "'");
        $defectOption = $process['id'] ? explode('，', $process['defectType']) : [];
        $json['data'] = "<div class='item_row'>" . hidden(array('name' => 'mxId[]', 'value' => self::getId())) . select(array('name' => 'problem[]', 'title' => '请选择', 'value' => '', 'option' => $defectOption)) . text(array('name' => 'num[]', 'other' => self::digitalFiltering('numPrecision'), 'title' => '数量', 'value' => '')) . "<span class='spanButton' style='margin-top: 0' onclick='decRow(this)'>删除</span></div>";
        return json_encode($json, 320);
    }

    /*编辑*/
    public function editEdit()
    {

        $id = $this->post('id') ?: self::getId();
        $problemArr = $this->post('problem') ?: [];
        $numArr = $this->post('num') ?: [];
        $mxIdArr = $this->post('mxId') ?: [];
        $teamStaffId = $this->post('teamStaffId');
        //赋值
        $field = array(
            "startTime" => $this->post('startTime'),
            "endTime" => $this->post('endTime'),
            "sendId" => $this->post('sendId'),//备注
            'fee' => $this->post('fee'),
            "yield" => $this->post('yield')?self::formattingFigure($this->post('yield'),'numPrecision'):'',
            "badNum" => $this->post('badNum')?self::formattingFigure($this->post('badNum'),'numPrecision'):'',
        );
        $machiningSendOrder = query('machining_send_order', "id = '$field[sendId]'");
        $field['materialId'] = $machiningSendOrder['materialId'];
        $field['processId'] = $machiningSendOrder['processId'];
        $field['routingId'] = $machiningSendOrder['routingId'];
        $field['routingMxId'] = $machiningSendOrder['routingMxId'];
        $field['companyId'] = $machiningSendOrder['companyId'];
        $field['unit'] = $machiningSendOrder['unit'];
        $routing_detail = query('routing_detail',"id = '$field[routingMxId]'");
        $field['valuationType'] = $routing_detail['valuationType'];
        $annotation = [
            "sendId" => '生产派工单',
            "yield" => '产量',
            "processId" => '工序',
            "materialId" => '物料ID',
            "routingId" => '工艺路线',
            "routingMxId" => '工艺路线明细',
            "valuationType" => '计件方式',
            "unit" => '单位',
        ];
        $rules = [
            "sendId" => 'required',
            "yield" => 'required|numeric',
            'processId' => 'required',
            "materialId" => 'required',
            "routingId" => 'required',
            'routingMxId' => 'required',
            "valuationType" => 'required',
            "unit" => 'required',
        ];

        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $info = query(self::table, " id = '" . $id . "' ");
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "权限不足";
        } elseif ($info['state'] == '已确认') {
            $json['warn'] = '此报工已确认，不能编辑';
        } else {
            $this->startTrans();
            if (empty($info['id'])) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'BG' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => " and coid = '".self::$coid."'",
                ],$field);
                $field = array_merge($field, array("id" => $id,'classify'=>'委外报工', 'coid' => self::$coid, 'orderNo' => $userNo, 'state' => '草稿', 'stid' => $this->control['stid']));
                $json['warn'] = insert(array("table" => self::table, "field" => $field));
            } else {
                $json['warn'] = update(array("table" => self::table, "field" => $field, "where" => "id = '$info[id]'"));
            }
            $newIdArr = [];
            if (is_array($mxIdArr)) {
                foreach ($mxIdArr as $k => $mxId) {
                    if (!empty($problemArr[$k])){
                        $newIdArr[] = $mxId;
                        $mx = query(self::tableMx, "id = '$mxId'");
                        if (!empty($mx['id'])) {
                            $warn = static::update(array(
                                'table' => self::tableMx,
                                'field' => array(
                                    'problem' => $problemArr[$k],
                                    'num' => $numArr[$k],
                                ),
                                'where' => "id = '$mx[id]'",
                            ));
                        } else {
                            $warn = static::insert(array(
                                'table' => self::tableMx,
                                'field' => array(
                                    'id' => $mxId,
                                    'coid' => self::$coid,
                                    'orderId' => $id,
                                    'problem' => $problemArr[$k],
                                    'num' => $numArr[$k],
                                ),
                            ));
                        }
                        if (!in_array($warn, array("新增成功", "更新成功"))) {
                            $json['warn'] = $warn;
                            break;
                        }
                    }
                }
            }
            if ($field['valuationType'] =='个人计件'){
                delete(array('table'=>'process_report_staff','where'=>"orderId = '$id'"));
                $warn = static::insert(array(
                    'table' => 'process_report_staff',
                    'field' => array(
                        'id' => suiji(),
                        'coid' => self::$coid,
                        'orderId' => $id,
                        'stid' => $teamStaffId,
                    ),
                ));
                if (!in_array($warn, array("新增成功", "更新成功"))) {
                    $json['warn'] = $warn;
                }
            }

            if (in_array($json['warn'], array("新增成功", "更新成功"))) {
                $this->commitTrans();
                delete(array('table' => self::tableMx, 'where' => " id not in ('" . implode("','", $newIdArr) . "') and orderId = '$id'"));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "ID：" . $id;
                $this->logText(array("type" => self::page, "text" => $text));
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
            } else {
                $this->rollback();
            }
        }

        $json['href'] = root . "control/adIndex.html?cla=" . self::page . "&fun=detail&id=" . $id;
        resp:
        return json_encode($json, 320);
    }

    /**
     * 生成质检单
     */
    private function qualityOrder($id): bool|string
    {
        $bool = true;
        $info = query(self::table,"id = '$id'");
        //获取当前工艺路线的工序是否质检
        $machining_send_order = query('machining_send_order', "id = '$info[sendId]'");
        $routing_detail = query('routing_detail', "id = '$info[routingMxId]'");
        if (in_array($routing_detail['method'],['免检','巡检','自检'])) {
            return $bool;
        }
        $process = query('process', "id = '$info[processId]'");
        if (empty($process['id'])) {
            return "未找到工序";
        }
        if (empty($process['qualityItem'])) {
            return "请填写工序【{$process['name']}】的质检项";
        }
        $id = self::getId();
        $field = [
            'id' => $id,
            'type' => 4,
            'coid' => self::$coid,
            'sourceTable' => self::table,
            'sourceId' => $info['id'],
            'targetId' => $info['companyId'],
            'inventoryId' => '',
            'warehouseId' => '',
            'num' => $info['yield'],
            'materialId' => $info['materialId'],
            'unit' => $machining_send_order['unit'],
            'qid' => '',
            'sourceNo' => $info['orderNo'],
            'sourceType' => '委外报工',
            'state' => '待质检',
        ];
        $userNo = codeTemplateClass::generateCode('processingInspection',[
            'prefix' => 'IF' . date('Ymd'),
            'table' => 'quality_order',
            'field' => 'orderNo',
            'where' => " and coid = '".self::$coid."'",
        ],$field);
        $field['orderNo'] = $userNo;
        $field['batch'] = $userNo . '-' . 1;
        $warn = static::insert(array(
            'table' => 'quality_order',
            'field' => $field
        ));
        if ($warn != '新增成功') {
            return "新增质检单失败";
        }
        $all = explode('，', $process['qualityItem']);
        foreach ($all as $val) {
            $warn = static::insert(array(
                'table' => 'quality_order_item',
                'field' => [
                    'id' => self::getId(),
                    'coid' => self::$coid,
                    'orderId' => $id,
                    'itemId' => $val,
                ]
            ));
            if ($warn != '新增成功') {
                return "新增质检单明细质检项目失败";
            }
        }
        return $bool;
    }

    /*出差详情*/
    public function detail(): string
    {
        //定义参数
        if (empty($this->get('id'))) {
            $html = '未找到此' . self::title;
        } else {
            $info = query(self::table, " id = '" . $this->get('id') . "' ");
            if (empty($info['id'])) {
                $html = "未找到此记录";
            } else {
                //菜单
                $data = array(
                    "id" => $info['id'],
                );

                $button = [];
                if ($info['state'] == '草稿') {
                    //按钮
                    $button[] = [
                        "name" => "提交",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                }
                if ($info['state'] != '已确认') {
                    if ($this->power(self::page, "edit")) {
                        //按钮
                        $button[] = [
                            "name" => "编辑",
                            "type" => "顶部页卡",
                            "title" => "编辑用户",
                            "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                        ];
                    }
                    if ($this->power(self::page, "del")) {
                        //按钮
                        $button[] = [
                            "name" => "删除",
                            "type" => "弹出层",
                            "cla" => $this->get('cla'),
                            "fun" => "operate",
                            "post" => ["act" => 'del', "id" => $info['id']],
                        ];
                    }
                }

                if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                    $button[] = [
                        "name" => "确认",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'confirm', "id" => $info['id']],
                        'style' => 'li-btn-blue-bg',
                    ];
                }
                if ($this->power(self::page, "confirm") && $info['state'] == '已确认') {
                    $button[] = [
                        "name" => "撤回",
                        "type" => "弹出层",
                        "cla" => $this->get('cla'),
                        "fun" => "operate",
                        "post" => ["act" => 'cancel', "id" => $info['id']],
                    ];
                }
                $button[] = [
                    "name" => "单据追踪",
                    "type" => "顶部页卡",
                    "title" => "单据追踪",
                    "url" => $this->root . "control/adIndex.html?cla=orderTrack&fun=home&orderType=委外报工&id=" . $info['id'],
                ];
                //操作记录
                $button[] = self::operateLogBut($info['id']);

                $machiningSendOrder = query('machining_send_order', "id = '$info[sendId]'");
                $process = query('process', "id = '$info[processId]'");
                $mxStr = find(array('table' => self::tableMx, "single" => "orderId = '$info[id]' group by orderId", 'field' => "group_concat(concat(any_value(problem),',',any_value(num))) as str"));
                $supplier = query('supplier', "id = '$info[companyId]'");
                //生成表单
                $data['html'] = $this->tableShow(array(
                    "button" => $button,
                    array(
                        array(
                            "报工单号" => $info['orderNo'],
                            '委外单位' => $supplier['name'],
                            "工序" => $process['name'],
                        ),
                        array(
                            "派工单号"=> $machiningSendOrder['orderNo'],
                            "派工单类型"=> $machiningSendOrder['type'],
                        ),
                        array(
                            "物料" => materialClass::getName($info['materialId']),
                            "生产数量" => self::lostZero($machiningSendOrder['num'],'numPrecision') . $info['unit'],
                        ),
                        array(
                            "计划开始时间" => $machiningSendOrder['startDate'],
                            "计划下线时间" => $machiningSendOrder['endDate'],
                        ),
                        array(
                            "备注" => $machiningSendOrder['text'],
                        ),
                    ),
                    '报工记录' => array(
                        array(
                            "加工费" => $info['fee'],
                        ),
                        array(
                            "不良数量" => self::lostZero($info['badNum'],'numPrecision'). $info['unit'],
                            "缺陷类型" => $mxStr['str']??'',
                            "开始结束时间" => $info['startTime'] . '至' . $info['endTime'],
                        ),
                        array(
                            "备注" => $info['text'],
                        ),
                    ),
                    '系统信息' => array(
                        array(
                            "创建人" => self::findStaff($info['stid']),
                            "创建时间" => $info['time'],
                        ),
                        array(
                            "状态" => $info['state']
                        ),
                    ),
                ));
                //生成页面
                $html = $this->tab($data);
            }
        }
        //返回
        return $html;
    }


    /**
     * 确认
     */
    public function confirmEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '已确认',
            'checkId' => self::$stid,
            'confirmTime' => $this->time,
        ];

        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = '你还没有确认权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此' . self::title;
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此' . self::title . '不是待确认状态，不能确认';
        } else {
            $this->startTrans();
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            $bool = $this->qualityOrder($info['id']);
            if ($bool !==true){
                $json['warn'] = $bool;
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                $this->commitTrans();
                auditClass::operateRecord($info['id'],'委外报工','确认');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '确认成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            } else {
                $this->rollback();
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 撤回
     */
    public function cancelEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '草稿',
            'checkId' => '',
            'confirmTime' => '',
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此委外报工';
        } elseif ($info['state'] != '已确认') {
            $json['warn'] = '此委外报工不是已确认状态，无需撤回';
        } elseif (static::total(array('table' => 'quality_order', "where" => "sourceId = '$info[id]' and coid = '" . self::$coid . "' and state ='已质检'")) > 0) {
            $json['warn'] = '此报工单已存在有已质检的单据，不能撤回';
        }else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //删除质检单
                delete(array('table' => 'quality_order_item', 'where' => "orderId in (select id from quality_order where sourceId = '$info[id]' and coid = '" . self::$coid . "')"));
                delete(array('table' => 'quality_order_reason', 'where' => "orderId in (select id from quality_order where sourceId = '$info[id]' and coid = '" . self::$coid . "')"));
                delete(array('table' => 'quality_order', 'where' => "sourceId = '$info[id]'"));
                auditClass::operateRecord($info['id'],'委外报工','撤回');
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '撤回成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($info['id'])) {
            $json['warn'] = '未找到此委外报工';
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = '此委外报工不是草稿状态，不能提交';
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow(array(
                    "type" => "委外报工",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】提交",
                    'job' => self::findStaffDepartment(self::$stid) . '-' . $this->controlJob['name'],
                    'staffName' => $this->control['name'],
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = '提交成功';
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = "删除失败：已确认，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = $word = '';
        switch ($act) {
            case 'confirm':
                $act = 'confirm';
                $msg = '确认';
                $title = '是否已确认此' . self::title . '，确认后将不可修改？';
                $function = 'confirmEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'commit':
                $act = 'edit';
                $msg = '编辑';
                $title = '是否确认提交此' . self::title . '？';
                $function = 'commitEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            case 'cancel':
                $act = 'cancel';
                $msg = '撤回';
                $title = '是否确认撤回此' . self::title . '？';
                $function = 'cancelEdit';
                $form = self::page . 'OperateForm, detailForm';
                $power = '';
                $word = true;
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'word' => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     *选择生产产品
     *
     * @return bool|string
     */
    public function addMaterial(): bool|string
    {
        $html =
            text(array("name" => "orderNo", "title" => "委外派工单号")) .
            text(array('name' => 'code', 'title' => '产品编码')) .
            text(array('name' => 'materialName', 'title' => '产品名称')) .
            text(array('name' => 'model', 'title' => '产品型号'));
        $button = "<input style='margin-left: 5px' onclick=\"addMaterial()\" type='button' class='searchSub' value='提交'>";
        $html = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button));
    }

    /**
     *添加物料
     */
    public function addMaterialSearch(): bool|string
    {
        $and = " and isClose = 0 and machiningOrderId not in (select id from machining_order where coid = '".self::$coid."' and isClose = 1)";
        $mAnd = '';
        $like = [
            'orderNo'=>$this->post('orderNo')
        ];
        $equal = [
            'coid' => self::$coid,
            'classify'=>'委外派工',
            'state' => '已确认',
        ];

        if ($this->post('code')) {
            $mAnd .= " and code like '%" . $this->post('code') . "%'";
        }
        if ($this->post('materialName')) {
            $mAnd .= " and name like '%" . $this->post('materialName') . "%'";
        }
        if ($this->post('model')) {
            $mAnd .= " and model like '%" . $this->post('model') . "%'";
        }
        if ($mAnd) {
            $and .= " and materialId in (select id from material where 1=1 {$mAnd})";
        }
        $where = search(["like" => $like, "=" => $equal]) . $and;
        $page = $this->page([
            "table" => "machining_send_order",
            "where" => $where,
            'pageNum' => 50,
            "order" => "orderNo desc",
        ]);
        //获取表头
        $tr[] = ['', '委外派工单号', '单据日期', '委外单位', '产品编码', '产品名称', '产品型号', '工序'];
        //获取记录
        foreach ($page['array'] as $array) {
            $material = query('material', "id = '$array[materialId]'");
            $supplier = query('supplier', "id = '$array[companyId]'");
            $process = query('process', "id = '$array[processId]'");
            $tr[] = array(
                "<input name='mxId' value='$array[id]' type='radio'>",
                $array['orderNo'],
                date('Y-m-d',strtotime($array['time'])),
                $supplier['name'],
                $material['code'],
                $material['name'],
                $material['model'],
                $process['name'],
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMaterialEdit(): bool|string
    {
        $id = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($id)) {
            $json['warn'] = '请选择生产计划单';
        } else {
            $machining_send_order = query('machining_send_order', "id = '$id'");
            $material = query('material', "id = '$machining_send_order[materialId]'");
            $line = query('product_line', "id = '$machining_send_order[lineId]'");
            $process = query('process', "id = '$machining_send_order[processId]'");
            $routingDetail = query('routing_detail',"id = '$machining_send_order[routingMxId]'");
            $supplier = query('supplier',"id = '$machining_send_order[companyId]'");
            $lineName = $line['workshop'] . '-' . $line['name'];
            $json['companyName'] = $supplier['name'];
            $json['process'] = $process['name'];
            $json['processId'] = $process['id'];
            $json['valuationType'] = $routingDetail['valuationType'];
            $json['planNum'] = self::formattingFigure($machining_send_order['num'],'numPrecision');
            $json['reportNum'] = find(array('table'=>self::table,'where'=>"sendId = '$machining_send_order[id]'",'sum'=>"yield"));
            $json['unit'] = $machining_send_order['unit'];
            $json['materialName'] = $material['code'] . '-' . $material['name'] . '-' . $material['model'];
            $json['id'] = $machining_send_order['id'];
            $json['orderNo'] = $machining_send_order['orderNo'];
            $json['lineName'] = $lineName;
            $json['problem'] = option(array('option' => $process['defectType'] ? explode('，', $process['defectType']) : [], 'title' => '请选择'));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

}
